<template>
  <div>
    <!-- 遮罩层 -->
    <div v-if="visible" class="overlay"></div>

    <!-- 聊天窗口：左侧边栏，右聊天区域  -->
    <div v-if="visible" class="chat-window" :class="{'sidebar-open': sidebarVisible}">
      <!-- 侧边栏 -->
      <div class="sidebar" v-if="sidebarVisible">
        <div class="sidebar-header">
          <img src="@\assets\cute_pet\社畜小狐狸\小狐狸.png" alt="加载失败" class="sidebar-avatar" />
          <span class="pet-name">社畜小狐狸</span>
          <div v-html="closeSidebar" class="close-sidebar" @click="toggleSidebar"></div>
        </div>
        <button class="new-conversation">
          <i v-html="newDialog" style="display:flex;margin-right:5px"></i>开启新对话
        </button>
        <div class="conversation-history">
          <span class="conversation-title">
            <el-icon style="margin-right:5px">
              <ChatDotSquare />
            </el-icon>最近对话
          </span>
          <div class="conversation-list" ref="conversationList">
            <div
              v-for="(message, index) in historyMessages"
              :key="index"
              class="conversation-item"
              @mouseover="showOptions(index)"
              @mouseleave="hideOptions(index)"
            >
              <div class="conversation-text">{{ message.text }}</div>
              <el-icon class="conversation-options" :class="{ 'visible': message.showOptions }">
                <MoreFilled />
              </el-icon>
            </div>
          </div>
        </div>
      </div>
      <!-- 聊天区域 -->
      <div class="main-chat-window">
        <!-- 切换宠物内容 -->
        <div v-if="showPetSelectionContent" class="pet-selection-content">
          <div class="pet-info-left"></div>
          <div class="pet-images-grid"></div>
        </div>

        <!-- 右侧聊天窗口————上，中，下 -->
        <div v-else class="user-chat">
          <!-- 上 -->
          <div class="chat-header">
            <div v-html="openSidebar" class="open-sidebar" @click="toggleSidebar"></div>
            <span class="chat-title">宠物小助手</span>
            <button class="close-button" @click="closeChat">关闭</button>
          </div>

          <!-- 中 -->
          <div class="chat-body" ref="chatBody">
            <div
              v-for="(message, index) in messages"
              :key="index"
              class="message"
              :class="{'user-message': message.sender === 'user', 'pet-message': message.sender === 'pet'}"
            >
              <img
                v-if="message.sender === 'pet'"
                src="@\assets\cute_pet\萌鼠嘟嘟\dudu.png"
                class="chat-avatar"
              />
              <div class="message-content" v-html="renderMarkdown(message.text)"></div>
              <img
                v-if="message.sender === 'user'"
                src="@\assets\user\user.jpg"
                class="chat-avatar"
              />
            </div>
          </div>

          <!-- 下 -->
          <div class="chat-input-container">
            <textarea v-model="userInput" @keyup.enter="sendMessage" placeholder="输入消息..." />
            <button :disabled="isSending" @click="sendMessage">
              <el-icon>
                <Top />
              </el-icon>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from "vue";
import { petChat } from "@/api/zhipuAI/zhipuAI";
import { marked } from "marked";
import { MoreFilled, ChatDotSquare } from "@element-plus/icons-vue";
import { Top } from "@element-plus/icons-vue";

marked.setOptions({
  breaks: true, //启用换行符解析
  gfm: true //启用GFM语法
});

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(["update:visible"]);

const userInput = ref("");
const messages = ref([
  { sender: "pet", text: "你好！我是你的宠物小助手，有什么我可以帮你的吗？" }
]);

const historyMessages = ref([
  { text: "调整布局和样式", showOptions: false },
  { text: "调整布局和样式", showOptions: false },
  { text: "调整布局和样式", showOptions: false },
  { text: "调整布局和样式", showOptions: false },
  { text: "调整布局和样式", showOptions: false }
]);

const showOptions = index => {
  historyMessages.value[index].showOptions = true;
};

const hideOptions = index => {
  historyMessages.value[index].showOptions = false;
};

const renameConversation = index => {
  // 实现重命名逻辑
  console.log(`重命名对话 ${index}`);
};

const deleteConversation = index => {
  // 实现删除逻辑
  messages.value.splice(index, 1);
};

const chatBody = ref(null);
const isSending = ref(false);
const sidebarVisible = ref(false);
const showPetSelectionContent = ref(false);

const openSidebar = ref(
  '<svg t="1742037455699" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3341" width="18" height="18"><path d="M127.6 259h768.9c35.4 0 64.1-28.7 64.1-64.1s-28.7-64.1-64.1-64.1H127.6c-35.4 0-64.1 28.7-64.1 64.1S92.2 259 127.6 259zM896.4 765H127.6c-35.4 0-64.1 28.7-64.1 64.1s28.7 64.1 64.1 64.1h768.9c35.4 0 64.1-28.7 64.1-64.1S931.8 765 896.4 765zM127.6 576.1H512c35.4 0 64.1-28.7 64.1-64.1s-28.7-64-64.1-64H127.6c-35.4 0-64.1 28.7-64.1 64.1s28.7 64 64.1 64zM938.8 477l-159.1-88.4c-28.2-15.6-62.8 4.7-62.7 36.9v176.7c0 32.2 34.6 52.6 62.8 36.9l159.1-88.4c28.8-15.9 28.8-57.6-0.1-73.7z" p-id="3342" fill="#ffffff"></path></svg>'
);
const closeSidebar = ref(
  '<svg t="1741535082109" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3584" width="20" height="20"><path d="M896 853.333333H128v-85.333333h768v85.333333zM341.76 226.901333L205.994667 362.666667l135.765333 135.765333-60.330667 60.330667L85.333333 362.666667l196.096-196.096L341.76 226.901333zM896 554.666667h-384v-85.333334h384v85.333334z m0-298.666667h-384V170.666667h384v85.333333z" fill="#8a8a8a" p-id="3585"></path></svg>'
);
const newDialog = ref(
  '<svg t="1741676403814" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3304" width="20" height="20"><path d="M738.0992 112.64a51.2 51.2 0 1 1 102.4 0v76.8h76.8a51.2 51.2 0 1 1 0 102.4h-76.8v76.8a51.2 51.2 0 1 1-102.4 0V291.84h-76.8a51.2 51.2 0 1 1 0-102.4h76.8V112.64z m155.4432 658.8928c-49.9712 49.9712-110.336 74.9568-180.992 74.9568h-141.7216L370.688 986.624a51.2 51.2 0 0 1-80.5376-41.9328v-98.9184c-61.5936-4.608-114.7904-29.2864-159.6928-74.24-49.9712-49.92-75.008-110.2848-75.008-180.992v-230.4c0-70.656 25.0368-131.0208 75.008-180.992 49.9712-49.9712 110.336-75.008 180.992-75.008h221.9008a51.2 51.2 0 0 1 0 102.4H311.4496a147.968 147.968 0 0 0-108.544 45.056 147.968 147.968 0 0 0-45.056 108.544v230.4c0 42.4448 15.0016 78.6432 45.056 108.6464a147.968 147.968 0 0 0 108.544 44.9536h29.9008a51.2 51.2 0 0 1 51.2 51.2v50.9952l132.7616-92.928a51.2 51.2 0 0 1 29.3376-9.216h157.9008a147.968 147.968 0 0 0 108.5952-45.056 147.968 147.968 0 0 0 45.0048-108.544v-115.2a51.2 51.2 0 1 1 102.4 0v115.2c0 70.656-24.9856 131.0208-75.008 180.992z" p-id="3305" fill="#409eff"></path></svg>'
);
const sendMessage = () => {
  if (userInput.value.trim() === "") return;

  const requestData = {
    content: userInput.value.trim(),
    isDiaryProcessing: false
  };

  messages.value.push({ sender: "user", text: userInput.value.trim() });

  userInput.value = "";

  // 设置发送状态
  isSending.value = true;

  // 添加一个空的 AI 消息对象
  const aiMessage = { sender: "", text: "" };
  messages.value.push(aiMessage);

  // 调用 petChat 接口
  petChat(requestData, feedback => {
    // 实时更新消息列表中的最后一条消息
    const lastMessageIndex = messages.value.length - 1;
    messages.value[lastMessageIndex].text = feedback;
    messages.value[lastMessageIndex].sender = "pet";
    nextTick(() => {
      chatBody.value.scrollTop = chatBody.value.scrollHeight;
    });
  })
    .then(() => {
      isSending.value = false;
      console.log("聊天AI回复消息为：");
      console.log(messages.value);
    })
    .catch(error => {
      console.error("发送消息时出错:", error);
      isSending.value = false;
    });
};

const closeChat = () => {
  emit("update:visible", false);
};

const toggleSidebar = () => {
  sidebarVisible.value = !sidebarVisible.value;
};

const changePet = () => {
  showPetSelectionContent.value = !showPetSelectionContent.value;
};

watch(
  () => props.visible,
  newVal => {
    if (newVal) {
      nextTick(() => {
        chatBody.value.scrollTop = chatBody.value.scrollHeight;
      });
    }
  }
);

// 渲染 Markdown 内容
const renderMarkdown = text => {
  return marked.parse(text);
};
</script>

<style scoped>
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 10000; /* 确保遮罩层在聊天窗口下方 */
}

.chat-window {
  position: fixed;
  top: 5%;
  left: 50%;
  width: 650px;
  height: 612px;
  background: #fff;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  z-index: 10001;
  transform: translateX(-50%);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.chat-window.sidebar-open {
  width: 850px;
  left: 50%;
  transform: translateX(-50%);
}

.sidebar {
  width: 200px;
  height: 100%;
  float: left;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(5px);
  border-right: 2px dashed var(--primary-color);
  padding: 10px;
  box-sizing: border-box;
}

.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.sidebar-avatar {
  border-radius: 50%;
  width: 45px;
  height: 45px;
}

.pet-name {
  font-size: 13px;
  color: #333;
  font-weight: bold;
  margin-left: -25px;
}

.close-sidebar {
  cursor: pointer;
  display: flex;
}

.new-conversation[data-v-f87d9c95] {
  width: 75%;
  padding: 10px;
  border: none;
  background: var(--secondary-color-pink) !important;
  color: var(--text-color) !important;
  border-radius: 15px !important;
  transition: all 0.3s ease;
  cursor: pointer;
  margin-bottom: 10px;
  font-size: 17px;
  align-items: center;
  display: flex;
}

.new-conversation:hover {
  background: var(--primary-color) !important;
  color: white !important;
}

.conversation-history {
  margin-bottom: 10px;
  margin-top: 25px;
}

.conversation-title[data-v-f87d9c95] {
  font-size: 15px;
  color: #333;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.conversation-list {
  height: 460px;
  overflow-y: auto;
}

.conversation-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 10px;
  cursor: pointer;
  margin-left: 10px;
}

.conversation-item:hover {
  background: var(--secondary-color-pink) !important;
  border-radius: 10px;
}

.conversation-text {
  flex: 1;
  margin-right: 10px;
  font-size: 13px;
  color: rgba(0, 0, 0, 0.5);
}

.conversation-options {
  display: flex;
  gap: 5px;
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s, opacity 0.3s ease-out;
  color: rgba(0, 0, 0, 0.5);
}

.conversation-options.visible {
  visibility: visible;
  opacity: 1;
}

.pet-info {
  display: flex;
  align-items: center;
}

.info-text {
  cursor: pointer;
  color: #1890ff;
}

.info-text:hover {
  background: #40a9ff;
}

.pet-selection-content {
  display: flex;
  flex-direction: row;
  height: 100%;
}

.pet-info-left {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #f1f1f1;
  padding: 20px 0px;
}

.pet-info-item {
  display: flex;
  justify-items: center;
  align-items: center; /* 垂直居中 */
  padding: 10px 20px;
  /* border-bottom: 1px solid #ddd; */
}

.change-pet-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.pet-images-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
}

.pet-image-item {
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  width: 150px;
}

.pet-image-item img {
  width: 100px;
  height: 100px;
  border-radius: 10px;
}

/* 右侧聊天窗口————上，中，下
 * 
 * 顶部标题栏
 *  
 *  
 */
.main-chat-window {
  height: 100%;
  overflow: hidden;
  background: linear-gradient(
    145deg,
    var(--pet-bubble) 0%,
    var(--secondary-color-blue) 100%
  );
}

.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: linear-gradient(
    135deg,
    var(--primary-color),
    var(--button-hover)
  );
  border-bottom: 1px solid var(--border-color);
  padding: 12px 20px;
  box-shadow: 0 4px 12px var(--shadow-color);
  position: relative;
  overflow: hidden;
}

.chat-header::before {
  /* 毛绒装饰线 */
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: repeating-linear-gradient(
    -45deg,
    var(--secondary-color-pink) 0px,
    var(--secondary-color-pink) 8px,
    var(--primary-color) 8px,
    var(--primary-color) 16px
  );
}

.chat-header .open-sidebar {
  display: flex;
  width: 30px;
  border-radius: 50%;
  cursor: pointer;
  align-items: center;
  justify-content: center;
}

.chat-header .chat-title {
  font-family: "Comic Neue", cursive;
  font-size: 20px;
  color: var(--secondary-color-pink);
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
  position: relative;
  padding-left: 30px;
  font-weight: bold;
}

.chat-header .chat-title::before {
  /* 爪印图标 */
  content: "🐾";
  position: absolute;
  left: 0;
  top: -2px;
  font-size: 24px;
  filter: drop-shadow(0 2px 2px var(--shadow-color));
  animation: pawJump 2s var(--ease-bubble) infinite;
}

@keyframes pawJump {
  0%,
  100% {
    transform: translateY(0) rotate(-8deg);
  }
  50% {
    transform: translateY(-8px) rotate(10deg);
  }
}

.chat-header .close-button {
  background: rgba(255, 255, 255, 0.9);
  padding: 6px 15px;
  border-radius: 15px;
  color: var(--button-hover);
  transition: all 0.3s var(--ease-bubble);
  border: 1px solid var(--border-color);
  cursor: pointer;
}

.chat-header .close-button:hover {
  transform: rotate(5deg);
  box-shadow: 0 2px 6px rgba(255, 107, 129, 0.3);
}

/* 
 * 
 * 展示消息的中间区域
 *  
 *  
 */
.chat-body {
  height: 470px;
  overflow-y: auto;
  padding: 20px;
  padding-bottom: 10px;
  position: relative;
  /* box-shadow: inset 0 0 30px var(--shadow-color); */
}

.message {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
  animation: messageIn 0.4s var(--ease-bubble);
}

@keyframes messageIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-content {
  position: relative;
  max-width: 70%;
  padding: 0 10px;
  margin-right: 10px;
  font-family: "Comic Neue", cursive;
  line-height: 1.6;
}

:deep(.message-content p) {
  margin: 6px 0 !important;
}

.message.user-message .message-content::before {
  border-top-color: var(--primary-color);
  right: -8px;
}

.message.pet-message .message-content::before {
  border-top-color: var(--pet-bubble);
  left: -8px;
}

.message.user-message {
  justify-content: flex-end;
}

.message.user-message .message-content {
  background: var(--primary-color);
  color: white;
  border-radius: 20px 4px 20px 20px;
  box-shadow: 2px 2px 8px var(--shadow-color);
  margin-right: 10px;
  transition: transform 0.3s var(--ease-bubble);
}

.message.user-message .message-content:hover {
  transform: translateX(-5px);
}

.message.pet-message {
  justify-content: flex-start;
}

.message.pet-message .message-content {
  background: var(--pet-bubble);
  border: 2px solid var(--border-color);
  border-radius: 4px 20px 20px 20px;
  color: var(--text-color);
  box-shadow: 2px 2px 12px rgba(255, 179, 198, 0.15);
  margin-left: 10px;
  transition: transform 0.3s var(--ease-bubble);
}

.message.pet-message .message-content:hover {
  transform: translateX(5px);
}

.message.pet-message .message-content::after {
  /* 宠物消息装饰元素 */
  content: "🌸";
  position: absolute;
  right: -25px;
  bottom: -10px;
  font-size: 24px;
  opacity: 0.6;
  animation: float 3s var(--ease-bubble) infinite;
  filter: drop-shadow(1px 1px 2px var(--shadow-color));
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0) rotate(-5deg);
  }
  50% {
    transform: translateY(-8px) rotate(5deg);
  }
}

.chat-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border: 2px solid var(--border-color);
  box-shadow: 0 2px 6px var(--shadow-color);
  animation: breath 2.5s var(--ease-bubble) infinite;
}

@keyframes breath {
  0%,
  100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

.chat-body::-webkit-scrollbar {
  /* 滚动条美化 */
  width: 8px;
  background: var(--secondary-color-pink);
  border-radius: 4px;
}

.chat-body::-webkit-scrollbar-thumb {
  background: var(--primary-color);
  border-radius: 4px;
  border: 2px solid var(--secondary-color-pink);
}

/* 
 * 
 * 底部发消息区域
 *  
 *  
 */

.chat-input-container[data-v-f87d9c95] {
  display: flex;
  align-items: center;
  backdrop-filter: blur(8px);
  overflow: hidden;
  position: relative;
  margin: 0 20px 10px 20px;
  transition: all 0.3s var(--ease-bubble);
  display: flex;
}

.chat-input-container textarea {
  flex: 1;
  padding: 8px 15px;
  color: var(--text-color);
  font-size: 15px;
  font-family: "Comic Neue", cursive;
  min-height: 75px;
  max-height: 150px;
  line-height: 1.4;
  resize: none;
  overflow-y: auto;
  transition: all 0.3s var(--ease-bubble);
  position: relative;
  z-index: 1;
  width: 200px;
  border: none;
  border: 2px solid var(--secondary-color-pink);
  box-shadow: inset 0 2px 4px var(--shadow-color),
    0 4px 12px -2px rgba(255, 179, 198, 0.1);
  border-radius: 20px;
}

.chat-input-container textarea:focus {
  box-shadow: inset 0 2px 6px var(--shadow-color), 0 0 12px var(--shadow-color);
  outline: none;
}

.chat-input-container textarea::placeholder {
  font-family: "Comic Neue", cursive;
  color: var(--button-hover);
  font-size: 15px;
  color: var(--button-hover);
  font-style: italic;
}

.chat-input-container textarea::-webkit-scrollbar {
  /* 自定义滚动条 */
  width: 8px;
  background: transparent;
}

.chat-input-container textarea::-webkit-scrollbar-thumb {
  background: var(--primary-color);
  border-radius: 4px;
  border: 2px solid var(--secondary-color-pink);
}

.chat-input-container textarea::-webkit-scrollbar-track {
  background: transparent;
}

.chat-input-container button {
  padding: 8px 20px;
  border: none;
  color: #fff;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background: var(--primary-color);
  border-radius: 20px;
  transition: all 0.3s var(--ease-bubble);
  border: 2px solid var(--secondary-color-pink);
  bottom: -18px;
  margin-left: 10px;
}

.chat-input-container button:hover {
  background: var(--button-hover);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px var(--shadow-color);
}

.chat-input-container button::after {
  content: "🐾";
  position: absolute;
  right: -20px;
  transition: all 0.3s ease;
  filter: drop-shadow(0 1px 1px var(--shadow-color));
}

.chat-input-container button:hover::after {
  right: 2px;
}
</style>